<template>
  <div>
    <!-- 评论输入框 -->
    <el-input v-model="commentContent" placeholder="发布评论..." />
    <el-button @click="postComment">发布评论</el-button>

    <div v-for="comment in comments" :key="comment.id" class="comment">
      <p>{{ comment.content }}</p>

      <!-- 回复列表 -->
      <div v-for="reply in comment.replies" :key="reply.id" class="reply">
        <p>{{ reply.content }}</p>
      </div>

      <!-- 回复输入框 -->
      <el-input v-model="replyContent[comment.id]" placeholder="回复该评论..." />
      <el-button @click="postReply(comment.id)">回复</el-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'; // 确保导入 axios

export default {
  data() {
    return {
      commentContent: '',
      replyContent: {},
      comments: []
    };
  },
  mounted() {
    this.loadComments();
  },
  methods: {
    async loadComments() {
      const response = await axios.get('/api/comments');
      this.comments = response.data;
      for (const comment of this.comments) {
        const replyResponse = await axios.get(`/api/replies/comment/${comment.id}`);
        comment.replies = replyResponse.data;
      }
    },
    async postComment() {
      if (!this.commentContent) return;
      const comment = {
        content: this.commentContent
      };
      await axios.post('/api/comments', comment);
      this.commentContent = '';
      this.loadComments();
    },
    async postReply(commentId) {
      const replyContent = this.replyContent[commentId];
      if (!replyContent) return;
      const reply = {
        commentId,
        content: replyContent
      };
      await axios.post('/api/replies', reply);
      this.replyContent[commentId] = '';
      this.loadComments();
    }
  }
};
</script>

<style scoped>
.comment {
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #ccc;
}

.reply {
  margin-left: 20px;
  padding: 5px;
  border: 1px solid #eee;
}
</style>
